import Taro from "@tarojs/taro";
import { useState } from "react";
import { ScrollView, Text, View } from "@tarojs/components";
import { useReactive, useUpdateEffect } from "ahooks";

import ByCol from "@/components/ui/ByCol";
import ByRow from "@/components/ui/ByRow";
import ByText from "@/components/ui/ByText";
import ByTabs from "@/components/ui/ByTabs";
import ByIcon from "@/components/ui/ByIcon";
import BySpin from "@/components/ui/BySpin";
import ByEmpty from "@/components/ui/ByEmpty";
import ByImage from "@/components/ui/ByImage";
import PopupProductDetail from "./PopupProductDetail";
import BySearchBar from "@/components/ui/BySearchBar";
import TreeMenu from "@/packageProject/components/TreeMenu";

import ApiMaterial from "@/api/material";
import useList from "@/hooks/useList";
import useFetch from "@/hooks/useFetch";

import type { ByPopupBottomEvent } from "@/components/ui/ByPopupBottom";

import {
  // MaterialAreaDetail,
  MaterialClassItem,
  MaterialDetailDTO,
  MaterialInfo,
} from "@/types/material";
import setting from "@/utils/setting";

type PopupShopProps = {
  // 1 主材选材, 2 家具选材, 3 灯具窗帘选材, 4 电器选材
  chooseType?: number | "";
  // 是否来自签报页面，是：隐藏区域
  from?: "report";
  intentCustomerId: number;
  item?: MaterialDetailDTO;
  onConfirm: (model: MaterialDetailDTO) => void;
};

type ProductProps = {
  source: MaterialInfo;
  selected?: MaterialDetailDTO;
};

type ProductEvent = {
  onSelected?: () => void;
  onChange?: (num: number) => void;
};

const Products = ({ source, onSelected }: ProductProps & ProductEvent) => {
  return (
    <View className="flex-none w-[240px] mb-2">
      <ByImage
        size={240}
        circle={false}
        lazyLoad={true}
        preview={false}
        className="shadow-black-1"
        src={
          source.materialPicture ? setting.host + source.materialPicture : ""
        }
        onClick={onSelected}
      />

      <View className="mt-2">
        <ByText lineClamp={2} className="text-sm">
          {source.materialName}
        </ByText>

        <ByText className="mt-1 mb-2 text-xs text-second w-full" truncated>
          <Text>{source.brandCategory}</Text>
          <Text>{source.spec}</Text>
          <Text>({source.unit})</Text>
        </ByText>
      </View>
    </View>
  );
};

/**
 * 备注:（甲方需求！）
 * 关于弹窗交互: 当存在搜索关键词时，左侧菜单栏失效，不参与搜索；
 * 为避免视觉与数据产生误差，当存在搜索关键词时，直接禁用左侧菜单
 */
export default ({
  item,
  from,
  chooseType = "",
  intentCustomerId,

  onConfirm,
  onCancel,
}: PopupShopProps & ByPopupBottomEvent) => {
  // 搜索条件
  const search = useReactive({
    isActive: true,
    keyword: "",
    // todo: 该指定未定
    priceName: "",
    materialClassCode: "",
    /**即选中的tab项 */
    usePriceName: "",
  });

  // 获取材料分类列表
  const { list: classTreeList } = useList<MaterialClassItem>(
    ApiMaterial.classTree,
    {
      defaultParams: [{ materialProCode: "ZC", chooseType }],
      onSuccess({ list }) {
        search.materialClassCode = list[0]["materialClassCode"];
      },
    }
  );

  // 获取升级价tabs
  const { data: tabList = [] } = useFetch<any[]>(
    ApiMaterial.materialPriceUpgrade,
    {
      defaultParams: [{ intentCustomerId }],
      onAfter: ({ list }: any) =>
        list.map((e) => ({ label: e.priceName, value: e.priceValue, ...e })),
      onSuccess(res) {
        search.usePriceName = res[0]["value"];
      },
    }
  );

  // 根据条件，获取材料列表
  const { loading, list, resetToFirst, nextPage } = useList<MaterialInfo>(
    ApiMaterial.list,
    { manual: true }
  );

  useUpdateEffect(() => {
    if (search.usePriceName) {
      resetToFirst(search);
    }
  }, [search.keyword, search.materialClassCode, search.usePriceName]);

  const [productId, setProductId] = useState<number>();

  const handldeScan = () => {
    Taro.scanCode({
      success(res) {
        setProductId(res.result as unknown as number);
      },
    });
  };

  const activeTab = tabList?.find((e) => e.value === search.usePriceName);
  return (
    <>
      <View>
        <ByRow align="center" className="py-2 px-3">
          <ByCol span="none" className="mr-3">
            <ByIcon name="Scan" size={36} onClick={handldeScan} />
          </ByCol>
          <ByCol span="auto">
            <BySearchBar
              circle
              className="bg-page mr-3"
              placeholder="输入材料名称检索"
              onConfirm={(e) => (
                (search.keyword = e), (search.materialClassCode = "")
              )}
              onClear={() => (
                (search.keyword = ""), (search.materialClassCode = "")
              )}
            />
          </ByCol>

          <ByIcon
            name="CloseCircle"
            size={42}
            className="text-second"
            onClick={onCancel}
          />
        </ByRow>

        <ByTabs
          capsule
          tabs={tabList || []}
          active={search.usePriceName}
          onChange={(e) => (search.usePriceName = e)}
          className="mb-3 mx-1 text-sm"
        />

        <ByRow>
          <ByCol span={3} className="h-[76vh]">
            <TreeMenu
              center
              list={classTreeList}
              valueKey="materialClassCode"
              labelKey="materialClassName"
              active={search.materialClassCode}
              onClick={(index) =>
                !search.keyword &&
                (search.materialClassCode =
                  classTreeList[index].materialClassCode)
              }
            />
          </ByCol>

          <ByCol span={9}>
            <ScrollView
              scroll-y
              onScrollToLower={nextPage}
              className="h-[76vh]"
            >
              {!loading && list.length == 0 && <ByEmpty />}

              <View className="flex flex-wrap justify-between px-3">
                {list.map((item) => (
                  <Products
                    source={item}
                    key={item.materialId}
                    onSelected={() => setProductId(item.materialId)}
                  />
                ))}
              </View>

              {loading && <BySpin />}
            </ScrollView>
          </ByCol>
        </ByRow>
      </View>

      {productId && (
        <PopupProductDetail
          showPrice
          selected={item}
          activeTab={activeTab}
          productId={productId}
          hiddenArea={from == "report"}
          onCancel={() => setProductId(undefined)}
          onConfirm={(e) => (onConfirm(e), setProductId(undefined))}
        />
      )}
    </>
  );
};
